<template>
	<view class="login-box">
		<!-- 用户图标 -->
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<!-- 登录按钮 -->
		<button type="warn" class="btn-default" open-type="getUserInfo" @getuserinfo="getUserInfo"> 一键登录 </button>
		<!-- 权限文本 -->
		<text class="login-tips"> 登录后尽享更多权益 </text>
	</view>
</template>

<script>
	import {mapMutations,mapState,} from 'vuex'
	export default {
		name: "my-login",
		data() {
			return {

			};
		},
		computed:{
			...mapState('m_user',['redirctInfo'])
		},
		methods:{
			...mapMutations('m_user',['updataUserInfo','updataToken','updataRedirectInfo']),
			getUserInfo(e){
				if(e.detail.errMsg !== "getUserInfo:ok") return uni.$showMsg('您还未授权登录！')
				this.updataUserInfo(e.detail.userInfo)
				
				this.getCode(e.detail)
			},
			async getCode(info){
				let {encryptedData,iv,rawData,signature } = info
				// 获取Code码
				let [err,res] = await uni.login().catch(err=>err)

				if( err || res.errMsg !== "login:ok") return $showMsg('登录失败！')
				
				const query = {
					code:res.code,
					encryptedData,
					iv,
					rawData,
					signature
				}
				// 换取token
				const {data:data} = await uni.$http.post('/api/public/v1/users/wxlogin',query)
				
				if(data.meta.status !== 200) return uni.$showMsg('登录失败！')
				
				// 保存token
				this.updataToken(data.message.token)
				this.redirectBack()
			},
			// 返回上一次浏览界面
			redirectBack(){
				if(this.redirectInfo && this.redirectInfo.openType === 'switchTab'){
					uni.switchTab({
						url:this.redirectInfo.from,
						eompeleten(){
							this.upataRedirectInfo(null)
						}
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	.login-box {
		height: 100vh;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		.btn-default {
			width: 90%;
			border-radius: 50rpx;
			margin: 30rpx 0;
		}
		.login-tips{
			font-size: 32rpx;
			color: gray;
		}
	}
</style>
